# -*- coding:utf-8 -*-
import base64
import codecs
import re
from trace import pickle
import time
import sys
import datetime
from jsonpath import jsonpath
import json

from common.MqSend import send_mq
from common.dama.damaUtil import dama
import request_cicc.util
from common.log import Logger
from my_dbUtil.dbInsert import soupDb
from request_cic.getCarModel import get_car_model
from request_epicc_vpn.MyAdapter import MyAdapter
from request_epicc_vpn.calcUserYears import calc_user_years
from request_epicc_vpn.dbUtil import get_session
from request_epicc_vpn.getDataNew import caclAcl, caclPremium, compare_date, compare_time40

from request_epicc_vpn.standard_flow.dt_init import dt_init
from request_epicc_vpn.translateJsonToPremiun import readJson
import traceback
from common import redisUtil
reload(sys)
sys.setdefaultencoding('utf-8')
global null, false, true
null = None
false = False
true = True
log=Logger()

def standard_main(renewal_data_dt,endDate=""):
    try:
        r=redisUtil.CRedis()
        log.error("start")
        srssion = get_session()
        sessBase = srssion['2']
        req_session = pickle.loads(codecs.decode(sessBase.encode(), "base64"))
        req_session.mount('https://', MyAdapter())
        insuranceTypeList = ""
        insure_id = renewal_data_dt['insureCarId']
        client = renewal_data_dt.get('client',None)
        if isinstance(renewal_data_dt['insuranceType'],dict):
            insuranceType = renewal_data_dt['insuranceType']
            group_id = insuranceType['insuranceTypeGroupId']

        elif isinstance(renewal_data_dt['insuranceType'],list):
            insuranceTypeList = renewal_data_dt['insuranceType']
            insuranceType = insuranceTypeList[0]
            group_id = insuranceType['insuranceTypeGroupId']

        redis_dt = r.get_vin(renewal_data_dt['vinNo'], "2")
        if redis_dt is not None:
            try:
                log.info(u'人保可以从redis中获取信息')
                dt = eval(redis_dt)
                get_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMCheck.do?comCode=32012105&frameNo="+dt['vinNo']+"&licenseNo="
                req_session.post(url=get_checkcode_url,verify=False).json()

                if insuranceTypeList=="":
                    price_res = caclPremium(dt, insuranceType, req_session)
                    if price_res['data'][0].get('errMessage') is not None:
                        log.error(price_res['data'][0].get('errMessage'))
                    log.error(u"开始解析保费信息")
                    PremiumInfo = readJson(price_res['data'][0]['biInsuredemandVoList'][0]['prpCitemKinds'],price_res['data'][0].get('ciInsureVOList',None ))
                    if PremiumInfo:
                            log.info(PremiumInfo)
                            # data=[开始时间,结束时间，座位数，组合id，车辆id，公司id]
                            data_list = [dt['ciStartDate'], dt['ciEndDate'], dt['seatCount'],group_id, insure_id, '2']
                            soupDb(PremiumInfo, data_list)
                            log.info(u'人保入库成功')
                            return None
                    else:
                            log.error(u"未知错误")
                            return price_res['data'][0].get('errMessage','未知错误')
                else:
                    for insuranceType in insuranceTypeList:
                        try:

                            insure_id = renewal_data_dt['insureCarId']
                            group_id = insuranceType['insuranceTypeGroupId']
                            price_res = caclPremium(dt, insuranceType, req_session)
                            if price_res['data'][0].get('errMessage') is not None:
                                log.error(price_res['data'][0].get('errMessage'))
                            log.error(u"开始解析保费信息")
                            PremiumInfo = readJson(price_res['data'][0]['biInsuredemandVoList'][0]['prpCitemKinds'],price_res['data'][0].get('ciInsureVOList', None))
                            if PremiumInfo:
                                log.info(PremiumInfo)
                                # data=[开始时间,结束时间，座位数，组合id，车辆id，公司id]
                                data_list = [dt['ciStartDate'], dt['ciEndDate'], dt['seatCount'], group_id, insure_id, '2']
                                soupDb(PremiumInfo, data_list)
                                log.info(u'人保入库成功')
                                send_mq(client, dt['licenseNo'], "", "1", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId","9999"),insuranceType.get("insuranceTypeGroup","0"))
                                # return None
                            else:
                                log.error(u"未知错误")
                                log.info(u"开始发送消息")
                                send_mq(client, dt['licenseNo'], price_res['data'][0].get('errMessage','未知错误'), "2", "2", renewal_data_dt['sessionId'],renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
                        except Exception,e:
                            log.error(traceback.format_exc())
                            send_mq(client, dt['licenseNo'], "未知错误", "2", "2", renewal_data_dt['sessionId'],renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
                    return None
            except:
                log.error(traceback.format_exc())
                if client is not None:
                    log.info(u"开始发送消息")
                    send_mq(client, dt['licenseNo'], "未知错误", "2", "2", renewal_data_dt['sessionId'],renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
                return "未知错误"


        dt = dt_init()
        if endDate=="":
            tomorrow = datetime.date.today() + datetime.timedelta(1)
            today = datetime.date.today()
            dt['ciStartDate'] = str(tomorrow)
            dt['ciEndDate'] = str(datetime.datetime.strptime((str(today.year + 1) + '-' + str(today.month) + '-' + str(today.day)),"%Y-%m-%d").date())
        else:
            endDate = datetime.datetime.strptime(endDate, "%Y-%m-%d").date()
            dt['ciStartDate'] = str(endDate)
            endDate = datetime.datetime.strptime((str(endDate.year + 1) + '-' + str(endDate.month) + '-' + str(endDate.day)),"%Y-%m-%d").date() + datetime.timedelta(-1)
            dt['ciEndDate'] = str(endDate)
        dt['vinNo'] = renewal_data_dt.get('vinNo', '')
        dt['licenseNo'] = renewal_data_dt.get('plateNumber', '')
        get_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMCheck.do?comCode=32012105&frameNo="+dt['vinNo']+"&licenseNo="
        get_checkcode_res = req_session.post(url=get_checkcode_url,verify=False).json()
        checkcode_res = jsonpath(get_checkcode_res, "$.data")
        dt['checkNo'] = checkcode_res[0][0]['checkNo']
        dt['checkCode'] = checkcode_res[0][0]['checkCode']
        #dt['checkAnswer'] = request_cicc.util.pic2Str(base64.b64decode(dt['checkCode']))
        dt['checkAnswer']=dama("3",dt['checkCode'])
        post_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMConfirm.do?comCode=32012105&checkNo="+dt['checkNo']+"&checkCode="+dt['checkAnswer']
        post_checkcode_res = req_session.post(url=post_checkcode_url,verify=False).json()
        post_checkcode_res = jsonpath(post_checkcode_res, "$.data")
        log.info(u'开始打码')
        count = 0
        while post_checkcode_res[0][0].get('errMessage', '') is not None:
            if '未匹配到交管车辆信息' in post_checkcode_res[0][0].get('errMessage',''):
                log.error("未匹配到交管车辆信息")
                #返回错误信息
                if client is not None:
                    log.info(u"开始发送消息")
                    send_mq(client, dt['licenseNo'], post_checkcode_res[0][0].get('errMessage',''), "2", "2", renewal_data_dt['sessionId'],renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
                return post_checkcode_res[0][0].get('errMessage','')
            if '录入的校验码有误' in post_checkcode_res[0][0].get('errMessage',''):
                dama("99",dt['checkCode'])
                log.error(u"验证码有误，错误的验证码为,%s" % dt['checkAnswer'])
                get_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMCheck.do?comCode=32012105&frameNo=" + dt['vinNo'] + "&licenseNo="
                get_checkcode_res = req_session.post(url=get_checkcode_url, verify=False).json()
                checkcode_res = jsonpath(get_checkcode_res, "$.data")
                dt['checkNo'] = checkcode_res[0][0]['checkNo']
                dt['checkCode'] = checkcode_res[0][0]['checkCode']
                #dt['checkAnswer'] = request_cicc.util.pic2Str(base64.b64decode(dt['checkCode']))
                dt['checkAnswer']=dama("3",dt['checkCode'])
                post_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMConfirm.do?comCode=32012105&checkNo=" + dt['checkNo'] + "&checkCode=" + dt['checkAnswer']
                post_checkcode_res = req_session.post(url=post_checkcode_url, verify=False).json()
                post_checkcode_res = jsonpath(post_checkcode_res, "$.data")
            if count>4:
                #验证码重发超限
                if client is not None:
                    log.info(u"开始发送消息")
                    send_mq(client, dt['licenseNo'], "查询失败，稍后重试", "2", "2", renewal_data_dt['sessionId'],renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
                return "查询失败，稍后重试"
            count = count + 1

        if post_checkcode_res[0][0].get('errMessage', '') is None:
            log.info(u'打码成功')
            dt['modelCode'] = post_checkcode_res[0][0]['modelCode']
            car_info_url = "http://10.134.136.112:8000/prpall/vehicle/vehicleQuery.do?brandName=" + dt['modelCode'] + "&modelCode="
            car_info_res = req_session.post(url=car_info_url, verify=False).json()
            car_info_list = jsonpath(car_info_res, "$.data")
            if car_info_list:
                if len(car_info_list[0])==0:
                    log.info(u"通过车架号人保无法获取车辆型号，正在通过调用中华联合接口获取车型")
                    cic_car_info = get_car_model(dt['vinNo'])
                    if cic_car_info is not None:
                        dt['gCIndustryModelName'] = cic_car_info['gCIndustryModelName']
                        car_info_url = "http://10.134.136.112:8000/prpall/vehicle/vehicleQuery.do?brandName=" + dt['gCIndustryModelName'] + "&modelCode="
                        car_info_res = req_session.post(url=car_info_url, verify=False).json()
                        car_info_list = jsonpath(car_info_res, "$.data")

                if len(car_info_list[0])>0:
                    log.info(u'获取车型成功，正在选取最低价车型')
                    car_info_list = car_info_list[0]
                    car_info_list.sort(key=lambda obj: obj.get('priceT'))
                    car_info = car_info_list[0]
                    if post_checkcode_res[0][0].get('enrollDate',None) is not None:
                        dt['enrollDate'] = str(time.strftime("%Y-%m-%d", time.localtime(int(post_checkcode_res[0][0]['enrollDate']['time']) / 1000)))
                    dt['licenseNo'] = post_checkcode_res[0][0]['id']['licenseNo']
                    dt['pmCarOwner'] = post_checkcode_res[0][0]['carOwner']
                    dt['exhaustScale'] = car_info['vehicleExhaust']
                    dt['engineNo'] = post_checkcode_res[0][0]['engineNo']
                    dt['brandName'] = car_info['vehicleName']
                    dt['purchasePriceOld'] = str(car_info['priceTr'])
                    log.info(u'新车购置价格是:%s' % dt['purchasePriceOld'])
                    dt['frameNo'] = dt['vinNo']
                    dt['modelCode'] = car_info['vehicleId']
                    dt['seatCount'] = car_info['vehicleSeat']
                    useYears = calc_user_years(dt['ciStartDate'], dt['enrollDate'])
                    dt['prpCitemCar_useYears'] = useYears
                    acl_price = caclAcl(dt, req_session)
                    dt['aclPrice'] = acl_price
                    price_res = caclPremium(dt, insuranceType, req_session)
                    while price_res['data'][0].get('errMessage') is not None:
                        if '重复投保' in price_res['data'][0].get('errMessage'):
                            str1 = "\d{4}-\d{2}-\d{2}"
                            datelist = re.findall(str1, price_res['data'][0]['errMessage'], re.S)
                            if len(datelist) == 2:
                                endDate = compare_date(datelist[0], datelist[1])
                                dayGap = compare_time40(str(endDate))
                                if dayGap >= 40:
                                    log.error(u"重复投保，上期保单超过40天")
                                    if client is not None:
                                        log.info(u"开始发送消息")
                                        send_mq(client, dt['licenseNo'], price_res['data'][0]['errMessage'], "2", "2",renewal_data_dt['sessionId'], renewal_data_dt['isPhone'],insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
                                    return price_res['data'][0]['errMessage']
                                else:
                                    dt['ciStartDate'] = str(endDate)
                                    endDate = datetime.datetime.strptime((str(endDate.year + 1) + '-' + str(endDate.month) + '-' + str(endDate.day)),"%Y-%m-%d").date() + datetime.timedelta(-1)
                                    dt['ciEndDate'] = str(endDate)
                                    useYears = calc_user_years(dt['ciStartDate'], dt['enrollDate'])
                                    dt['prpCitemCar_useYears'] = useYears
                                    acl_price = caclAcl(dt, req_session)
                                    dt['aclPrice'] = acl_price
                                    price_res = caclPremium(dt, insuranceType, req_session)
                            else:
                                log.error(u"重复投保")
                                if client is not None:
                                    log.info(u"开始发送消息")
                                    send_mq(client, dt['licenseNo'], price_res['data'][0]['errMessage'], "2", "2",renewal_data_dt['sessionId'], renewal_data_dt['isPhone'],insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
                                return price_res['data'][0]['errMessage']
                    log.error(u"开始解析保费信息")
                    PremiumInfo = readJson(price_res['data'][0]['biInsuredemandVoList'][0]['prpCitemKinds'],price_res['data'][0].get('ciInsureVOList',None ))
                    if PremiumInfo:
                        log.info(PremiumInfo)
                        # data=[开始时间,结束时间，座位数，组合id，车辆id，公司id]
                        data_list = [dt['ciStartDate'], dt['ciEndDate'], dt['seatCount'],group_id, insure_id, '2']
                        soupDb(PremiumInfo, data_list)
                        dt['ciEndDate'] = str( dt['ciEndDate'])
                        r.set_vin(dt['vinNo'], "2", json.dumps(dt, ensure_ascii=False))
                        log.info(u'人保入库成功')
                        if insuranceTypeList!="":
                            insuranceTypeList = insuranceTypeList[1:]
                            for insuranceType in insuranceTypeList:
                                try:
                                    insure_id = renewal_data_dt['insureCarId']
                                    group_id = insuranceType['insuranceTypeGroupId']
                                    price_res = caclPremium(dt, insuranceType, req_session)
                                    if price_res['data'][0].get('errMessage') is not None:
                                        log.error(price_res['data'][0].get('errMessage'))
                                    log.error(u"开始解析保费信息")
                                    PremiumInfo = readJson(
                                        price_res['data'][0]['biInsuredemandVoList'][0]['prpCitemKinds'],
                                        price_res['data'][0].get('ciInsureVOList', None))
                                    if PremiumInfo:
                                        log.info(PremiumInfo)
                                        # data=[开始时间,结束时间，座位数，组合id，车辆id，公司id]
                                        data_list = [dt['ciStartDate'], dt['ciEndDate'], dt['seatCount'], group_id,insure_id, '2']
                                        soupDb(PremiumInfo, data_list)
                                        log.info(u'人保入库成功')
                                        log.info(u"开始发送消息")
                                        send_mq(client, dt['licenseNo'], "", "1", "2", renewal_data_dt['sessionId'],renewal_data_dt['isPhone'],insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
                                        # return None
                                    else:
                                        log.error(u"未知错误")
                                        log.info(u"开始发送消息")
                                        send_mq(client, dt['licenseNo'], price_res['data'][0].get('errMessage', '未知错误'),"2", "2", renewal_data_dt['sessionId'], renewal_data_dt['isPhone'],insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
                                except Exception, e:
                                    log.error(traceback.format_exc())
                                    log.info(u"开始发送消息")
                                    send_mq(client, dt['licenseNo'], "未知错误", "2", "2", renewal_data_dt['sessionId'],renewal_data_dt['isPhone'],insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
                        return None
                    else:
                        return "未知错误"
                else:
                    log.error(u'无法获取车型')
                    if client is not None:
                        send_mq(client, dt['licenseNo'], '无法获取车型', "2", "2",renewal_data_dt['sessionId'], renewal_data_dt['isPhone'],insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
                    return ('无法获取车型')
    except Exception,e:
        log.error(traceback.format_exc())
        if client is not None:
            send_mq(client, dt['licenseNo'], '未知错误', "2", "2", renewal_data_dt['sessionId'],renewal_data_dt['isPhone'], insuranceType.get("insuranceTypeGroupId", "9999"),insuranceType.get("insuranceTypeGroup", "0"))
        return "未知错误"

if __name__=="__main__":
    standard_main()